# -*- coding:utf-8 -*-

from dbbasic import dbMgr
from Models import User

def save(user):
	if isinstance(user,User):
		with dbMgr() as cursor:
			#cursor.execute('create table user(id integer primary key autoincrement, name varchar(200), email varchar(200))')
			cursor.execute('insert into user values(null,?,?)', (user.name,user.email))
	if isinstance(user, unicode) or isinstance(user, str):
		with dbMgr() as cursor:
			cursor.execute('insert into user values(null,?)', (user,))
		
def get(userId):
	with dbMgr() as cursor:
		cursor.execute('select * from user where id=?', (userId,))
		value = cursor.fetchone()
		user = User(*value[1:])
		user.id = value[0]
		return user
		
def list():
	with dbMgr() as cursor:
		cursor.execute('select * from user')
		values = cursor.fetchall()
		users = []
		for v in values:
			user = User(*v[1:])
			user.id = v[0]
			users.append(user)
		return users

def update(user):
	if user.id == None:
		print 'id is null, must save first'
		return
	
	with dbMgr() as cursor:
		cursor.execute('update user set name=?,email=? where id=?', (user.name,user.email,user.id))
		
def delete(user):
	if isinstance(user, User):
		if user.id == None:
			print 'id is null, must save first'
			return
		with dbMgr() as cursor:
			cursor.execute('delete from user where id=?', (user.id,))
			
	if isinstance(user, int):
		with dbMgr() as cursor:
			cursor.execute('delete from user where id=?', (user,))